function local_corr_AVA(simType,outputPath, noIt,layers,corr_cell_tot,xMax,yMax,zMax,weight_den,weight_vp,weight_vs,sgemsStrut, nullDataValues)
%% FROM THE CORRELATION CUBES SAVE WEIGHTED LOCAL CORRELATION
%
% corr_cell_tot [cell]- CELL WITH CORRELATIONS. BEST CORRELATION {2,1}
% 
% NO OUTPUT. CORRELATION CUBES ARE SAVED DIRECTLY TO HD.
%
% MODIFICATIONS:
% 21 APR 2014 - PERFORMANCE UPDATE
% 11 SEP 2012 - WEIGHT FOR DENSITY ADDED
%
% LA - 10 SEP 2012
%

%% ALLOCATE AND INITIALIZE
best_cc_den = zeros(xMax,yMax,zMax,'double');    
best_cc_vp  = zeros(xMax,yMax,zMax,'double');    
best_cc_vs  = zeros(xMax,yMax,zMax,'double');    

size_grid=size(corr_cell_tot{1,1});

%% CREATES BEST CORRELATION CUBES FOR DENSITY, Vp AND Vs
for j=1:size_grid(1)
    for i=1:size_grid(2)
       
        corr_cell_tot{2,1}{j,i}(find(isnan(corr_cell_tot{2,1}{j,i}) == 1)) = nullDataValues; % SAVED CORRELATIONS ARE ALWAYS >0
        
        ind=1;
        for n=1:size(layers,1)

            best_cc_den(j,i,ind:ind+layers(n)-1)    = sum(weight_den.*corr_cell_tot{2,1}{j,i}(n,:),2,'omitnan');
            best_cc_vp(j,i,ind:ind+layers(n)-1)     = sum(weight_vp.*corr_cell_tot{2,1}{j,i}(n,:),2,'omitnan');
            best_cc_vs(j,i,ind:ind+layers(n)-1)     = sum(weight_vs.*corr_cell_tot{2,1}{j,i}(n,:),2,'omitnan');
            
            ind=ind+layers(n,1);
            
        end
    end
end
clear j i;


%% WRITES BEST CUBES IN GSLIB FORMAT
if (strcmp(simType ,'SGEMS') == 1);
    
    sgemsStrut.grid_name        = 'CC';
    sgemsStrut.property{1}      = 'BCC';
    
    sgemsStrut.data             = best_cc_den(:);
    sgems_write([outputPath,'best_cc_den',num2str(noIt),'.sgems'], sgemsStrut);
    
    sgemsStrut.data             = best_cc_vp(:);
    sgems_write([outputPath,'best_cc_vp',num2str(noIt),'.sgems'], sgemsStrut);
    
    sgemsStrut.data             = best_cc_vs(:);
    sgems_write([outputPath,'best_cc_vs',num2str(noIt),'.sgems'], sgemsStrut);

else
    grid2gslib(best_cc_den,[outputPath,'best_cc_den',num2str(noIt),'.out']);
    grid2gslib(best_cc_vp, [outputPath,'best_cc_vp',num2str(noIt),'.out']);
    grid2gslib(best_cc_vs,[outputPath,'best_cc_vs',num2str(noIt),'.out']);
end

end